package com.xin.web;

import com.xin.pojo.Book;
import com.xin.pojo.Cart;
import com.xin.pojo.CartItem;
import com.xin.service.BookService;
import com.xin.service.impl.BookServiceimpl;
import com.xin.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CartServlet extends BaseServlet {
    private BookService bookService=new BookServiceimpl();

    /*
     向购物车中添加商品
     */
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart;
        int id = Integer.parseInt(req.getParameter("id"));
        Book book = bookService.queryBookById(id);
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());
         cart =(Cart) req.getSession().getAttribute("cart");
        if (cart==null) {
             cart=new Cart();
        }
        cart.addItem(cartItem);
        req.getSession().setAttribute("lastName",cartItem.getName());
        req.getSession().setAttribute("cart",cart);
        resp.sendRedirect(req.getHeader("Referer"));
    }
    /*
     清空购物车
     */
    protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart!=null){
            cart.clear();
            resp.sendRedirect(req.getHeader("Referer"));
        }
    }
    /*
        修改购物车中某商品的数量
     */
    protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int count = WebUtils.parseInt(req.getParameter("count"), 1);
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart!=null){
            cart.updateItem(id,count);
            resp.sendRedirect(req.getHeader("Referer"));
        }

    }
}
